<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>产品追溯信息</title>
    <!-- 引入Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 引入Inter字体 -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <script>
        // 配置Tailwind
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3b82f6',
                        secondary: '#10b981',
                        accent: '#f97316',
                        neutral: '#f3f4f6',
                        'neutral-dark': '#e5e7eb',
                        'text-primary': '#1e293b',
                        'text-secondary': '#64748b'
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                    animation: {
                        'float': 'float 6s ease-in-out infinite',
                        'pulse-slow': 'pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite',
                        'bounce-slow': 'bounce 2s infinite',
                    },
                    keyframes: {
                        float: {
                            '0%, 100%': { transform: 'translateY(0)' },
                            '50%': { transform: 'translateY(-10px)' },
                        }
                    }
                },
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .bg-gradient-fresh {
                background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
            }
            .card-hover {
                @apply transition-all duration-300 hover:shadow-lg hover:-translate-y-1;
            }
            .text-balance {
                text-wrap: balance;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
        }
    </style>
</head>
<body class="font-inter bg-gradient-to-br from-blue-50 to-indigo-50 min-h-screen flex items-center justify-center p-4 md:p-6 text-text-primary">
    <div class="container max-w-4xl w-full bg-white rounded-2xl shadow-xl overflow-hidden transform transition-all duration-500 animate-fade-in">
        <!-- 头部区域 -->
        <div class="relative overflow-hidden bg-gradient-to-r from-blue-500 to-indigo-600 text-white p-6 md:p-8">
            <!-- 装饰元素 -->
            <div class="absolute top-0 left-0 w-full h-full overflow-hidden opacity-10">
                <div class="absolute -top-10 -left-10 w-40 h-40 rounded-full bg-white animate-float"></div>
                <div class="absolute top-20 right-10 w-24 h-24 rounded-full bg-white animate-float" style="animation-delay: 1s"></div>
                <div class="absolute bottom-10 left-1/3 w-32 h-32 rounded-full bg-white animate-float" style="animation-delay: 2s"></div>
            </div>
            
            <div class="relative z-10 text-center">
                <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-white/20 backdrop-blur-sm mb-4 mx-auto">
                    <i class="fa fa-qrcode text-3xl"></i>
                </div>
                <h1 class="text-[clamp(1.5rem,3vw,2.25rem)] font-bold mb-2">产品追溯信息</h1>
                <p class="text-blue-100 max-w-md mx-auto">扫描二维码，轻松获取产品全生命周期信息，让每一件产品都可追溯</p>
            </div>
        </div>
        
        <!-- 内容区域 -->
        <div class="p-6 md:p-8" id="content">
            <!-- 加载状态 -->
            <div class="loading text-center py-16" id="loading">
                <div class="inline-block w-12 h-12 border-4 border-blue-100 border-t-primary rounded-full animate-spin mb-4"></div>
                <p class="text-text-secondary">正在加载产品信息...</p>
            </div>
        </div>
        
        <!-- 页脚 -->
        <div class="bg-neutral py-4 px-6 text-center">
            <p class="text-text-secondary text-sm">© 2024 产品追溯系统 | 透明可追溯，品质有保障</p>
        </div>
    </div>

    <!-- 图片预览模态框 -->
    <div id="imageModal" class="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 hidden items-center justify-center p-4">
        <button id="closeModal" class="absolute top-4 right-4 text-white text-3xl hover:text-accent transition-colors">
            <i class="fa fa-times"></i>
        </button>
        <div class="max-w-5xl w-full max-h-[90vh] flex items-center justify-center">
            <img id="modalImage" src="" alt="产品图片预览" class="max-w-full max-h-[90vh] object-contain rounded-lg">
        </div>
    </div>

    <script>
        // 获取URL参数
        function getUrlParam(name) {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get(name);
        }
        
        // 格式化时间
        function formatTime(timestamp) {
            if (!timestamp) return '未知';
            const date = new Date(timestamp * 1000);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }
        
        // 生成媒体HTML
        function generateMediaHTML(mediaArray, type) {
            if (!mediaArray || mediaArray.length === 0) {
                return `
                    <div class="no-media bg-neutral rounded-xl p-8 text-center text-text-secondary italic border border-dashed border-neutral-dark">
                        <i class="fa fa-camera text-4xl mb-3 opacity-50"></i>
                        <p>暂无${type === 'images' ? '图片' : '视频'}</p>
                    </div>
                `;
            }
            
            return mediaArray.map(item => {
                const time = formatTime(item.createtime);
                if (type === 'images') {
                    return `
                        <div class="media-item bg-white rounded-xl overflow-hidden shadow-sm border border-neutral-dark card-hover">
                            <img src="${item.image_url}" alt="审核图片" onclick="showImage('${item.image_url}')" 
                                 class="w-full h-40 object-cover transition-transform duration-500 hover:scale-105" loading="lazy">
                            <div class="media-caption p-3 bg-neutral text-xs text-text-secondary text-center">
                                ${time}
                            </div>
                        </div>
                    `;
                } else {
                    return `
                        <div class="media-item bg-white rounded-xl overflow-hidden shadow-sm border border-neutral-dark card-hover">
                            <video controls preload="metadata" class="w-full h-40 object-cover">
                                <source src="${item.image_url}" type="video/mp4">
                                您的浏览器不支持视频播放。
                            </video>
                            <div class="media-caption p-3 bg-neutral text-xs text-text-secondary text-center">
                                ${time}
                            </div>
                        </div>
                    `;
                }
            }).join('');
        }
        
        // 显示图片模态框
        function showImage(imageUrl) {
            const modal = document.getElementById('imageModal');
            const modalImage = document.getElementById('modalImage');
            
            modalImage.src = imageUrl;
            modal.classList.remove('hidden');
            modal.classList.add('flex');
            document.body.style.overflow = 'hidden';
            
            // 点击模态框背景关闭
            modal.onclick = function(e) {
                if (e.target === modal) {
                    closeModal();
                }
            };
            
            // ESC键关闭
            document.addEventListener('keydown', function handleEsc(e) {
                if (e.key === 'Escape') {
                    closeModal();
                    document.removeEventListener('keydown', handleEsc);
                }
            });
        }
        
        // 关闭模态框
        function closeModal() {
            const modal = document.getElementById('imageModal');
            modal.classList.add('hidden');
            modal.classList.remove('flex');
            document.body.style.overflow = '';
        }
        
        // 复制文本到剪贴板
        function copyToClipboard(text, element) {
            navigator.clipboard.writeText(text).then(() => {
                const originalText = element.innerHTML;
                element.innerHTML = '<i class="fa fa-check text-secondary mr-1"></i>已复制';
                element.classList.add('bg-secondary/10', 'text-secondary');
                element.classList.remove('bg-blue-50', 'text-primary');
                
                setTimeout(() => {
                    element.innerHTML = originalText;
                    element.classList.remove('bg-secondary/10', 'text-secondary');
                    element.classList.add('bg-blue-50', 'text-primary');
                }, 2000);
            });
        }
        
        // 显示产品信息
        function displayProductInfo(data) {
            const content = document.getElementById('content');
            
            let mediaHTML = '';
            
            // 如果有媒体数据，添加媒体显示区域
            if (data.item_media && data.item_media.length > 0) {
                mediaHTML = `
                    <div class="media-section mt-8 pt-6 border-t border-neutral-dark">
                        <h3 class="text-xl font-semibold mb-6 flex items-center">
                            <i class="fa fa-photo text-primary mr-2"></i>
                            媒体记录
                        </h3>
                        ${data.item_media.map((itemMedia, index) => `
                            <div id="item-${encodeURIComponent(itemMedia.item_no)}" class="media-group bg-neutral/50 rounded-2xl p-5 mb-6 transition-all duration-300 hover:shadow-md">
                                <div class="media-title font-medium text-lg mb-4 flex items-center">
                                    <i class="fa fa-cube text-primary/70 mr-2"></i>
                                    产品编号: ${itemMedia.item_no}
                                </div>
                                
                                <div class="mb-4">
                                    <h4 class="font-medium text-text-secondary mb-3 flex items-center">
                                        <i class="fa fa-image text-primary/70 mr-2"></i>
                                        审核图片
                                    </h4>
                                    <div class="media-grid grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
                                        ${generateMediaHTML(itemMedia.audit_images, 'images')}
                                    </div>
                                </div>
                                
                                <div>
                                    <h4 class="font-medium text-text-secondary mb-3 flex items-center">
                                        <i class="fa fa-video-camera text-primary/70 mr-2"></i>
                                        审核视频
                                    </h4>
                                    <div class="media-grid grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
                                        ${generateMediaHTML(itemMedia.audit_videos, 'videos')}
                                    </div>
                                </div>
                            </div>
                        `).join('')}
                    </div>
                `;
            }
            
            content.innerHTML = `
                <div class="mb-6">
                    <div class="flex items-center justify-between mb-4">
                        <h2 class="text-xl font-semibold flex items-center">
                            <i class="fa fa-info-circle text-primary mr-2"></i>
                            基本信息
                        </h2>
                        <span class="text-xs px-3 py-1 bg-green-100 text-green-800 rounded-full">
                            <i class="fa fa-check-circle mr-1"></i>已审核
                        </span>
                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div class="info-item bg-white rounded-xl p-4 border border-neutral-dark card-hover">
                            <div class="info-label text-text-secondary text-sm font-medium mb-1">追溯码</div>
                            <div class="info-value flex items-center justify-between">
                                <span>${data.trace_code || '未知'}</span>
                                <button onclick="copyToClipboard('${data.trace_code || ''}', this)" 
                                        class="text-xs px-2 py-1 rounded-full bg-blue-50 text-primary hover:bg-blue-100 transition-colors">
                                    <i class="fa fa-copy mr-1"></i>复制
                                </button>
                            </div>
                        </div>
                        
                        <div class="info-item bg-white rounded-xl p-4 border border-neutral-dark card-hover">
                            <div class="info-label text-text-secondary text-sm font-medium mb-1">订单号</div>
                            <div class="info-value">${data.order_no || '未知'}</div>
                        </div>
                        
                        <div class="info-item bg-white rounded-xl p-4 border border-neutral-dark card-hover">
                            <div class="info-label text-text-secondary text-sm font-medium mb-1">客户名称</div>
                            <div class="info-value">${data.customer_name || '未知'}</div>
                        </div>
                        
                        <div class="info-item bg-white rounded-xl p-4 border border-neutral-dark card-hover">
                            <div class="info-label text-text-secondary text-sm font-medium mb-1">产品名称</div>
                            <div class="info-value">${data.product_name || '未知'}</div>
                        </div>
                        
                        <div class="info-item bg-white rounded-xl p-4 border border-neutral-dark card-hover">
                            <div class="info-label text-text-secondary text-sm font-medium mb-1">产品型号</div>
                            <div class="info-value">${data.model_name || '未知'}</div>
                        </div>
                        
                        <div class="info-item bg-white rounded-xl p-4 border border-neutral-dark card-hover">
                            <div class="info-label text-text-secondary text-sm font-medium mb-1">报工数量</div>
                            <div class="info-value">${data.quantity || '0'}</div>
                        </div>
                    </div>
                </div>
                
                <div class="mb-6">
                    <h2 class="text-xl font-semibold mb-4 flex items-center">
                        <i class="fa fa-industry text-primary mr-2"></i>
                        生产信息
                    </h2>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div class="info-item bg-blue-50 rounded-xl p-4 border border-blue-100 card-hover">
                            <div class="info-label text-text-secondary text-sm font-medium mb-1">关联工序</div>
                            <div class="info-value">${data.process_name || '未知'}</div>
                        </div>
                        
                        <div class="info-item bg-purple-50 rounded-xl p-4 border border-purple-100 card-hover">
                            <div class="info-label text-text-secondary text-sm font-medium mb-1">提交员工</div>
                            <div class="info-value">${data.worker_name || '未知'}</div>
                        </div>
                        
                        <div class="info-item bg-purple-50 rounded-xl p-4 border border-purple-100 card-hover">
                            <div class="info-label text-text-secondary text-sm font-medium mb-1">审核员工</div>
                            <div class="info-value">${data.auditor_name || '未知'}</div>
                        </div>
                        
                        <div class="info-item bg-green-50 rounded-xl p-4 border border-green-100 card-hover">
                            <div class="info-label text-text-secondary text-sm font-medium mb-1">审核时间</div>
                            <div class="info-value">${formatTime(data.audit_time)}</div>
                        </div>
                        
                        <div class="info-item bg-white rounded-xl p-4 border border-neutral-dark card-hover md:col-span-2">
                            <div class="info-label text-text-secondary text-sm font-medium mb-1">报工备注</div>
                            <div class="info-value">${data.report_remark || '无备注'}</div>
                        </div>
                        
                        <div class="info-item bg-white rounded-xl p-4 border border-neutral-dark card-hover md:col-span-2">
                            <div class="info-label text-text-secondary text-sm font-medium mb-1">产品编号</div>
                            <div class="info-value flex flex-wrap gap-2 mt-1">
                                ${data.item_nos_array && data.item_nos_array.length > 0 
                                    ? data.item_nos_array.map(itemNo => 
                                        `<a href="#item-${encodeURIComponent(itemNo)}" 
                                            class="px-3 py-1 bg-blue-50 text-primary text-sm rounded-full hover:bg-blue-100 transition-colors"
                                            onclick="scrollToItem('${encodeURIComponent(itemNo)}')">
                                            ${itemNo}
                                        </a>`
                                      ).join('')
                                    : '未知'
                                }
                            </div>
                        </div>
                    </div>
                </div>
                
                ${mediaHTML}
            `;
        }
        
        // 显示错误信息
        function displayError(message) {
            const content = document.getElementById('content');
            content.innerHTML = `
                <div class="error text-center py-12">
                    <div class="w-16 h-16 bg-red-100 text-red-500 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fa fa-exclamation-triangle text-2xl"></i>
                    </div>
                    <p class="text-red-500 font-medium">${message}</p>
                    <button onclick="loadProductInfo()" class="mt-4 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
                        <i class="fa fa-refresh mr-1"></i>重试
                    </button>
                </div>
            `;
        }
        
        // 加载产品信息
        async function loadProductInfo() {
            // 显示加载状态
            const content = document.getElementById('content');
            content.innerHTML = `
                <div class="loading text-center py-16">
                    <div class="inline-block w-12 h-12 border-4 border-blue-100 border-t-primary rounded-full animate-spin mb-4"></div>
                    <p class="text-text-secondary">正在加载产品信息...</p>
                </div>
            `;
            
            const traceId = getUrlParam('id');
            
            if (!traceId) {
                displayError('缺少追溯ID参数');
                return;
            }
            
            console.log('开始加载追溯信息，ID:', traceId);
            
            try {
                // 模拟API请求
                // 实际使用时替换为真实API地址
                setTimeout(() => {
                    // 模拟返回数据
                    const mockData = {
                        code: 1,
                        data: {
                            trace_code: "TRC" + Math.random().toString(36).substring(2, 10).toUpperCase(),
                            order_no: "ORD" + Math.floor(Math.random() * 1000000),
                            customer_name: "示例客户有限公司",
                            product_name: "智能控制模块",
                            model_name: "ICM-2023-V2",
                            quantity: Math.floor(Math.random() * 100) + 10,
                            process_name: "最终质量检测",
                            worker_name: "张三",
                            auditor_name: "李四",
                            audit_time: Math.floor(Date.now() / 1000) - Math.floor(Math.random() * 86400 * 3),
                            report_remark: "产品外观完好，性能测试通过，符合出厂标准",
                            item_nos_array: [
                                "ITEM" + Math.floor(Math.random() * 10000),
                                "ITEM" + Math.floor(Math.random() * 10000),
                                "ITEM" + Math.floor(Math.random() * 10000)
                            ],
                            item_media: [
                                {
                                    item_no: "ITEM" + Math.floor(Math.random() * 10000),
                                    audit_images: [
                                        { image_url: "https://picsum.photos/seed/prod1/400/300", createtime: Math.floor(Date.now() / 1000) - 3600 },
                                        { image_url: "https://picsum.photos/seed/prod2/400/300", createtime: Math.floor(Date.now() / 1000) - 3500 }
                                    ],
                                    audit_videos: []
                                }
                            ]
                        }
                    };
                    
                    displayProductInfo(mockData.data);
                }, 1500);
                
                // 实际API请求代码
                /*
                const response = await fetch(`/api/scanwork/getTraceInfo?id=${traceId}`);
                const result = await response.json();
                
                if (result.code === 1) {
                    displayProductInfo(result.data);
                } else {
                    displayError(result.msg || '获取产品信息失败');
                }
                */
            } catch (error) {
                console.error('加载产品信息失败:', error);
                displayError('网络错误，请稍后重试');
            }
        }
        
        // 滚动到指定产品编号的函数
        function scrollToItem(encodedItemNo) {
            const element = document.getElementById(`item-${encodedItemNo}`);
            if (element) {
                // 添加高亮效果
                element.classList.add('ring-2', 'ring-primary', 'ring-offset-2');
                
                // 滚动到元素
                element.scrollIntoView({ 
                    behavior: 'smooth', 
                    block: 'start' 
                });
                
                // 移除高亮效果
                setTimeout(() => {
                    element.classList.remove('ring-2', 'ring-primary', 'ring-offset-2');
                }, 2000);
            }
        }
        
        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', () => {
            // 关闭模态框事件监听
            document.getElementById('closeModal').addEventListener('click', closeModal);
            
            // 加载产品信息
            loadProductInfo();
        });
    </script>
</body>
</html>
